package cn.wolfcode.wolf2w.resolver;

import cn.wolfcode.wolf2w.annotation.UserParam;
import cn.wolfcode.wolf2w.domain.UserInfo;
import cn.wolfcode.wolf2w.redis.service.IUserInfRedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;

/**
 * 用于解析请求映射方法中声明的当前登录用户的对象信息
 */
public class UserInfoArgumentResolver implements HandlerMethodArgumentResolver {
    @Autowired
    private IUserInfRedisService userInfoRedisService;

    //表示当前解析器能解析哪种类型参数
    //返回值boolean 类型: true:表示支持解析指定类型 false: 表示不支持指定类型
    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.getParameterType() == UserInfo.class
                && parameter.hasParameterAnnotation(UserParam.class);
    }

    //执行参数解析逻辑, 并注入到参数中
    //执行前提: 必须满足supportsParameter方法返回true
    @Override
    public Object resolveArgument(MethodParameter parameter,
                                  ModelAndViewContainer mavContainer,
                                  NativeWebRequest webRequest,
                                  WebDataBinderFactory binderFactory) throws Exception {
        //获取当前登录对象
        HttpServletRequest req = webRequest.getNativeRequest(HttpServletRequest.class);
        String token = req.getHeader("token");
        //返回值就是请求映射方法声明形式参数什么的UserInfo对象的值
        //返回当前登录用户对象
        return userInfoRedisService.getUserByToken(token);
    }
}
